#!/usr/bin/env node

const http   = require('http'),
      Koa    = require('koa'),
      Koas   = require('koa-static'),
      Router = require('koa-router'),
      fs     = require('fs');
let app    = new Koa(),
    router = new Router(),
    html   = fs.readFileSync('./chapters.html').toString('utf8'),
    data   = require('./data.js').chapterList;

data = data.sort(compare1('publishTimer'));
data = data.sort(compare2('publishTimer'));
data = data.sort(compare3('publishTimer'));
data = data.reverse();

function compare1(property){

  return function(a,b){
    console.log(a[property].split('-'));
    let value1 = a[property].split('-')[0];
    let value2 = b[property].split('-')[0];
    return value1-value2;
  }
}
function compare2(property){

  return function(a,b){
    let value1 = a[property].split('-')[1];
    let value2 = b[property].split('-')[1];
    return value1-value2;
  }
}
function compare3(property){

  return function(a,b){
    let value1 = a[property].split('-')[2];
    let value2 = b[property].split('-')[2];
    return value1-value2;
  }
}

app.use(Koas('./'));

router.get('/getlist', async(ctx,next)=>{
  ctx.type = 'application/json';
  ctx.body = JSON.stringify(data);
  next();
})

app.use(async (ctx, next)=>{
  if(ctx.request.path === '/'){
    ctx.type = 'text/html;charset=utf-8';
    ctx.body = fs.createReadStream('./chapters.html'); 
  }else{
    ctx.type = 'text/html';
    ctx.body = `<h1>Not Found</h1>`;
  }
  next();
});

app.use(router.routes());

app.listen(8080);

//http.createServer((req,res)=>{
//  let addr = url.parse(req.url);
//
//  if(addr.pathname ==='/'){
//    res.writeHead(200, {
//      'Content-Type':'text/html;charset=utf-8',
//      'Content-Length':Buffer.byteLength(html)
//    });
//
//  }else if(addr.pathname === '/getlist'){
//    res.writeHead(200,{
//      'content-type':'application/json'  
//    });
//    res.end(JSON.stringify(data));
//  }else{
//    res.statusCode = 404;
//    res.setHeader('Content-Type','text/html');
//    res.end('<h1>Not Found!</h1>');
//    return;
//  }
//
//  res.end(html);
//  fs.readFile('.'+ req.url,(err,data)=>{
//    res.end(data);
//  })
//
//}).listen(8080);
